from datetime import datetime
import re


def process_datetime_with_regex_and_format(txt, pat):
    try:
        re_output = list(re.search(pat, txt).groups())
        if not re_output:
            return ""
        if re_output[3] is None:
            re_output[3] = "00:00:00"
        if len(re_output[3]) == 5:
            re_output[3] += ":00"
        date_str = f"{re_output[0]}-{re_output[1]}-{re_output[2]} {re_output[3]}"
        return datetime.strftime(
            datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S"
        )
    except Exception as e:
        return ""


def parse_date(date_str):
    """
    处理日期时间数据，将其转换为标准的YYYY-MM-DD HH:mm:ss格式

    Args:
        date_str (str): 日期字符串

    Returns:
        str: 标准格式的日期字符串，如果输入为空则返回空字符串
    """
    regex_datetime_formats = (
        r"(\d{4})年(\d{1,2})月(\d{1,2})日\s*(\d{2}:\d{2}(?::\d{2})?)?",
        r"(\d{4})-(\d{1,2})-(\d{1,2})\s*(\d{2}:\d{2}(?::\d{2})?)?",
        r"(\d{4})/(\d{1,2})/(\d{1,2})\s*(\d{2}:\d{2}(?::\d{2})?)?",
        r"(\d{4}).(\d{1,2}).(\d{1,2})\s*(\d{2}:\d{2}(?::\d{2})?)?",
        r"-(\d{4})-\s+(\d{2})/(\d{2})\s+(\d{2}:\d{2})",
    )
    # 如果为空值，直接返回
    # date_str = find_datetime_str(date_str)
    if not date_str:
        return ""
    if not date_str or date_str.strip() == "":
        return ""

    def process_datetime_with_regex_and_format(txt, pat):
        try:
            re_output = list(re.search(pat, txt).groups())
            if not re_output:
                return ""
            if re_output[3] is None:
                re_output[3] = "00:00:00"
            if len(re_output[3]) == 5:
                re_output[3] += ":00"
            date_str = f"{re_output[0]}-{re_output[1]}-{re_output[2]} {re_output[3]}"
            return datetime.strftime(
                datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S"
            )
        except Exception as e:
            return ""

    date_str = date_str.strip()
    for pat in regex_datetime_formats:
        ret = process_datetime_with_regex_and_format(date_str, pat)
        if ret:
            return ret
    # 如果尝试转换失败，返回原值
    return ""


# print(parse_date("2025年9月"))
